/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.webapp.unit;

import cz.fi.muni.diplomka.common.Unit;
import cz.fi.muni.diplomka.common.enumeration.BuildingType;
import cz.fi.muni.diplomka.common.enumeration.ResourceType;
import cz.fi.muni.diplomka.common.enumeration.UnitType;
import cz.muni.fi.diplomka.servicelayer.dto.BuildingInCity;
import cz.muni.fi.diplomka.servicelayer.dto.City;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityBuildingManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityResourcesManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityUnitsManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityBuildingManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityResourcesManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityUnitsManagerImpl;
import cz.muni.fi.diplomka.servicelayer.xmlconvertors.UnitConvertor;
import cz.muni.fi.diplomka.webapp.layout.LinkPanel;
import cz.muni.fi.diplomka.webapp.market.CountValidator;
import cz.muni.fi.diplomka.webapp.resource.ResourcesPage;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

/**
 *
 * @author Jakub Kutil
 */
public class UnitPage extends WebPage {

    private CityResourcesManager cityResourcesManager = new CityResourcesManagerImpl();
    private CityUnitsManager cityUnitsManager = new CityUnitsManagerImpl();
    private CityBuildingManager cityBuildingManager = new CityBuildingManagerImpl();
    private CityManager cityManager = new CityManagerImpl();
    private String selectedCity = "";
    private List<String> cities;

    public UnitPage(PageParameters parameters) {
        final Long id;

        add(new FeedbackPanel("feedback"));

        if (parameters.containsKey("id")) {
            id = Long.parseLong(parameters.getString("id"));
            PageParameters p = new PageParameters();
            p.add("id", parameters.getString("id"));
            add(new LinkPanel("linkPanel", p));


            cities = new ArrayList<>();
            for (City c : cityManager.getCitiesByPlayerId(id)) {
                cities.add(c.getName());
            }
            if (parameters.containsKey("cityName")) {
                selectedCity = parameters.getString("cityName");
            }

            if (selectedCity.equals("")) {
                selectedCity = cities.get(0).toString();
            }

            final DropDownChoice<String> city = new DropDownChoice<>("city",
                    new PropertyModel<String>(this, "selectedCity"), cities);


            if (parameters.containsKey("unitName") && parameters.containsKey("count")) {
                boolean ok = true;
                int unitCount = parameters.getInt("count");
                UnitConvertor unitConvertor = new UnitConvertor();
                Unit unit = unitConvertor.getUnitFromXML(parameters.getString("unitName"));
                Long cityId = cityManager.getCityByName(selectedCity).getId();
                for (ResourceType resourceType : unit.getEquipment()) {
                    if (cityResourcesManager.getResourceCount(cityId, resourceType) < unitCount) {
                        error("Not enough of " + resourceType.toString() + ". You have "
                                + cityResourcesManager.getResourceCount(cityId, resourceType)
                                + ", but you need " + unitCount + ".");
                        ok = false;
                    }
                }
                if (cityResourcesManager.getResourceCount(cityId, ResourceType.Gold) < unitCount * unit.getPriceFood()) {
                    error("Not enough of " + ResourceType.Gold.toString() + ". You have "
                            + cityResourcesManager.getResourceCount(cityId, ResourceType.Gold)
                            + ", but you need " + unitCount * unit.getPriceGold() + ".");
                    ok = false;
                }
                if (cityResourcesManager.getResourceCount(cityId, ResourceType.Food) < unitCount * unit.getPriceGold()) {
                    error("Not enough of " + ResourceType.Food.toString() + ". You have "
                            + cityResourcesManager.getResourceCount(cityId, ResourceType.Food)
                            + ", but you need " + unitCount * unit.getPriceFood() + ".");
                    ok = false;
                }
                for (BuildingInCity b : cityBuildingManager.getAllBuildingsInCityOfType(cityId, BuildingType.Barracks)) {
                    if (b.getLevel() < unit.getLevel()) {
                        error("Your barracks are only level " + b.getLevel() + ", but you need level " + unit.getLevel() + " barracks to train " + unit.getName() + ".");
                        ok = false;
                    }
                }
                if (ok == true) {
                    for (ResourceType resourceType : unit.getEquipment()) {
                        cityResourcesManager.lowerResource(cityId, resourceType, unitCount);
                    }

                    cityResourcesManager.lowerResource(cityId, ResourceType.Gold, unitCount * unit.getPriceGold());
                    cityResourcesManager.lowerResource(cityId, ResourceType.Food, unitCount * unit.getPriceFood());

                    cityUnitsManager.increaseUnitCount(cityId, unit.getName(), unitCount);
                    info("You have recruited " + unitCount + " of " + unit.getName());
                }
            }
            Form<?> form = new Form<Void>("form") {
                @Override
                protected void onSubmit() {
                    selectedCity = cities.get(Integer.parseInt(city.getValue()));
                    PageParameters pageParameters = new PageParameters();
                    pageParameters.add("id", id.toString());
                    pageParameters.add("cityName", selectedCity);
                    setResponsePage(ResourcesPage.class, pageParameters);
                }
            };

            add(form);
            form.add(city);
            add(new Label("cityName", selectedCity));

            List<Unit> list = new ArrayList<>();

            UnitConvertor unitConvertor = new UnitConvertor();
            for (UnitType unitType : UnitType.values()) {
                list.add(unitConvertor.getUnitFromXML(unitType.toString()));
            }

            ListView listview = new ListView("listview", list) {
                @Override
                protected void populateItem(ListItem item) {
                    final Unit unit = (Unit) item.getModelObject();
                    item.add(new Label("name", unit.getName().toString()));
                    item.add(new Label("health", unit.getHealth() + ""));
                    item.add(new Label("attack", unit.getAttack() + ""));
                    item.add(new Label("defense", unit.getDefense() + ""));
                    item.add(new Label("damage", unit.getDamageLow() + "-" + unit.getDamageHigh()));
                    item.add(new Label("armor", unit.getArmor() + ""));
                    item.add(new Label("initiative", unit.getInitiative() + ""));
                    item.add(new Label("speed", unit.getSpeed() + ""));
                    item.add(new Label("carry", unit.getCarry() + ""));
                    item.add(new Label("level", unit.getLevel() + ""));

                    String equipment = "";
                    for (ResourceType resourceType : unit.getEquipment()) {
                        equipment += resourceType.toString() + " ";
                    }

                    item.add(new Label("neededEquipment", equipment));
                    item.add(new Label("price", "Food: " + unit.getPriceFood() + " Gold: " + unit.getPriceGold()));

                    final RequiredTextField<String> count = new RequiredTextField<>("count", Model.of("0"));
                    count.add(new CountValidator());

                    item.add(count);

                    Form<?> hire = new Form<Void>("hire") {
                        @Override
                        protected void onSubmit() {
                            PageParameters pageParameters = new PageParameters();
                            pageParameters.add("id", id.toString());
                            pageParameters.add("unitName", unit.getName().toString());
                            pageParameters.add("count", count.getValue());
                            setResponsePage(UnitPage.class, pageParameters);
                        }
                    };
                    hire.add(count);
                    item.add(hire);
                }
            };
            add(listview);
        }
    }
}
